import 'dart:io';

import 'package:flutter/services.dart';
import 'package:xindong/common/xindong_all.dart';
import 'package:xindong/common/xindong_app_info.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:url_launcher/url_launcher_string.dart';

class XinDongToNativePlugin {
  static const getOAID = "getOaid";
  static const getLocationEnable = "globalLocationEnable";
  static const openGPS = "daKaiGPS";
  static const openAppStore = "openAppStore"; // ios显示商店

  Future callNativeMethod(String methodName, {dynamic arguments}) async {
    try {
      const channel = MethodChannel("com.xindong.zhitgx");
      return await channel.invokeMethod(methodName, arguments);
    } catch (e) {
      mCatchPrint(e);
      return Future.error(e.toString());
    }
  }

  // android
  void getAndroidOAID() async {
    if (Platform.isIOS) return;
    try {
      XinDongAppDeviceInfo.instance.deviceOAID = await callNativeMethod(getOAID);
      mDebugPrint("Android OAID：${XinDongAppDeviceInfo.instance.deviceOAID}");
    } catch (e) {
      mCatchPrint(e);
    }
  }

  // android 检测是否开启位置服务
  Future<bool> enablePositioningSystem() async {
    if (Platform.isIOS) {
      return true;
    }
    try {
      return await callNativeMethod(getLocationEnable);
    } catch (e) {
      mCatchPrint(e);
    }
    return Future.value(false);
  }

  Future openGPSSettings() async {
    if (Platform.isIOS) {
      return;
    }
    try {
      return await callNativeMethod(openGPS);
    } catch (e) {
      mCatchPrint(e);
    }
    return Future.value(false);
  }

  void initLink() async {
    try {
      callNativeMethod("initLink");
    } catch (e) {
      mCatchPrint(e);
    }
  }

  void initBeauty() async {
    try {
      callNativeMethod("initBeauty");
    } catch (e) {
      mCatchPrint(e);
    }
  }

  void saveBeauty() async {
    try {
      callNativeMethod("saveBeauty");
    } catch (e) {
      mCatchPrint(e);
    }
  }

  // 安卓通道数据
  Future androidChannelData() async {
    try {
      if (Platform.isIOS) {
        return;
      }
      String result = await callNativeMethod("channelData");
      mDebugPrint("安卓渠道 $result");
      XinDongAll.instance.androidChannel = result;
    } catch (e) {
      return null;
    }
  }

  // 显示应用商店
  Future showApplicationStore({String url = ""}) async {
    try {
      if (Platform.isIOS && url.contains("itunes.apple.com")) {
        callNativeMethod(openAppStore, arguments: {"itunes": url});
      } else {
        launchUrlString(url);
      }
    } catch (e) {
      mCatchPrint(e);
      return null;
    }
  }

  // 单例公开访问点
  factory XinDongToNativePlugin() => _singletonClass();

  // 静态私有成员，没有初始化
  static XinDongToNativePlugin? _instance;

  static XinDongToNativePlugin get instance => _singletonClass();

  // 私有构造函数
  XinDongToNativePlugin._();

  // 静态、同步、私有访问点
  static XinDongToNativePlugin _singletonClass() {
    _instance ??= XinDongToNativePlugin._();
    return _instance!;
  }
}
